<template>
  <el-form
      ref="clueRefForm"
      :model="clueQuery"
      :rules="clueRules"
      label-width="100px"
      style="max-width: 95%;">

    <el-form-item label="负责人">
      <el-select
          v-model="clueQuery.owner_id"
          placeholder="请选择负责人"
          style="width: 100%"
          clearable
          disabled>
        <el-option
            v-for="item in ownerOptions"
            :key="item.id"
            :label="item.name"
            :value="item.id"/>
      </el-select>
    </el-form-item>

    <el-form-item label="所属活动">
      <el-select
          v-model="clueQuery.activity_id"
          placeholder="请选择所属活动"
          style="width: 100%"
          clearable>
        <el-option
            v-for="item in activityOptions"
            :key="item.id"
            :label="item.name"
            :value="item.id"/>
      </el-select>
    </el-form-item>

    <el-form-item label="姓名" prop="full_name">
      <el-input v-model="clueQuery.full_name"/>
    </el-form-item>

    <el-form-item label="称呼">
      <el-select
          v-model="clueQuery.appellation"
          placeholder="请选择称呼"
          style="width: 100%"
          clearable>
        <el-option
            v-for="item in appellationOptions"
            :key="item.id"
            :label="item.type_value"
            :value="item.id"/>
      </el-select>
    </el-form-item>

    <el-form-item label="手机" v-if="clueQuery.id > 0"><!--此时是编辑-->
      <el-input v-model="clueQuery.phone" disabled/>
    </el-form-item>

    <el-form-item label="手机" prop="phone" v-else><!--此时是录入-->
      <el-input v-model="clueQuery.phone"/>
    </el-form-item>

    <el-form-item label="微信">
      <el-input v-model="clueQuery.weixin"/>
    </el-form-item>

    <el-form-item label="QQ" prop="qq">
      <el-input v-model="clueQuery.qq"/>
    </el-form-item>

    <el-form-item label="邮箱" prop="email">
      <el-input v-model="clueQuery.email"/>
    </el-form-item>

    <el-form-item label="年龄" prop="age">
      <el-input v-model="clueQuery.age"/>
    </el-form-item>

    <el-form-item label="职业">
      <el-input v-model="clueQuery.job"/>
    </el-form-item>

    <el-form-item label="年收入" prop="year_income">
      <el-input v-model="clueQuery.year_income"/>
    </el-form-item>

    <el-form-item label="住址">
      <el-input v-model="clueQuery.address"/>
    </el-form-item>

    <el-form-item label="贷款">
      <el-select
          v-model="clueQuery.need_loan"
          placeholder="请选择是否需要贷款"
          style="width: 100%"
          clearable>
        <el-option
            v-for="item in needLoanOptions"
            :key="item.id"
            :label="item.type_value"
            :value="item.id"/>
      </el-select>
    </el-form-item>

    <el-form-item label="意向状态">
      <el-select
          v-model="clueQuery.intention_state"
          placeholder="请选择意向状态"
          style="width: 100%"
          clearable>
        <el-option
            v-for="item in intentionStateOptions"
            :key="item.id"
            :label="item.type_value"
            :value="item.id"/>
      </el-select>
    </el-form-item>

    <el-form-item label="意向产品">
      <el-select
          v-model="clueQuery.intention_product"
          placeholder="请选择意向产品"
          style="width: 100%"
          clearable>
        <el-option
            v-for="item in productOptions"
            :key="item.id"
            :label="item.name"
            :value="item.id"/>
      </el-select>
    </el-form-item>

    <el-form-item label="线索状态">
      <el-select
          v-model="clueQuery.state"
          placeholder="请选择线索状态"
          style="width: 100%"
          clearable>
        <el-option
            v-for="item in clueStateOptions"
            :key="item.id"
            :label="item.type_value"
            :value="item.id"/>
      </el-select>
    </el-form-item>

    <el-form-item label="线索来源">
      <el-select
          v-model="clueQuery.source"
          placeholder="请选择线索来源"
          style="width: 100%"
          clearable>
        <el-option
            v-for="item in sourceOptions"
            :key="item.id"
            :label="item.type_value"
            :value="item.id"/>
      </el-select>
    </el-form-item>

    <el-form-item label="线索描述" prop="description">
      <el-input
          v-model="clueQuery.description"
          :rows="5"
          type="textarea"
          placeholder="请输入线索描述"/>
    </el-form-item>

    <el-form-item label="下次联系时间">
      <el-date-picker
          v-model="clueQuery.next_contact_time"
          type="datetime"
          style="width: 100%;"
          value-format="YYYY-MM-DD HH:mm:ss"
          placeholder="请选择下次联系时间"/>
    </el-form-item>

    <el-form-item>
      <el-button type="primary" @click="addClueSubmit">提 交</el-button>
      <el-button type="success" plain @click="goBack(router)">返 回</el-button>
    </el-form-item>
  </el-form>
</template>

<script setup>
import {goBack, messageTip} from "../util/util.js";
import router from "../router/router.js";
import {inject, onMounted, reactive, ref} from "vue";
import {doGet, doPost, doPut} from "../http/httpRequest.js";
import {useRoute} from "vue-router";

let route = useRoute();
const reload = inject("reload");

let clueRefForm = ref();
//线索表单对象，初始值是空
let clueQuery = reactive({});
//负责人的下拉选项
let ownerOptions = ref([{}]);
//市场活动的下拉选项数据，初始值是空
let activityOptions = ref([{}]);
//意向产品的下拉选项
let productOptions = ref([{}]);
let appellationOptions = ref([{}]);
let needLoanOptions = ref([{}]);
let intentionStateOptions = ref([{}]);
let clueStateOptions = ref([{}]);
let sourceOptions = ref([{}]);

onMounted(()=>{
  loadDicValue('appellation');
  loadDicValue('needLoan');
  loadDicValue('intentionState');
  loadDicValue('clueState');
  loadDicValue('source');
  loadDicValue('activity');
  loadDicValue('product');
  loadOwner();
  loadLoginUser();
  loadClue();
})
//检查手机格式方法
const checkPhone = (rule, value, callback) => {
  console.log(rule)
  console.log(value) // value 就是我们input框里面输入的手机号
  console.log(callback)
  //验证该手机号是否已经录入过，如果录入过了，就不能再录入了
  let phone = value; // value 就是我们input框里面输入的手机号
  if (phone) {
    doGet("/api/clue/" + phone, {}).then(resp => {
      if (resp.data.code === 500) {
        //手机号录入过了，不能再录入了
        return callback(new Error('该手机号录入过了，不能再录入.'))
      } else {
        return callback(); //验证通过了，直接调用一下callback()函数
      }
    })
  }
}
//录入线索验证规则
let clueRules = {
      phone : [
        { required: true, message: '请输入手机号码', trigger: 'blur' },
        { pattern : /^1[3-9]\d{9}$/, message: '手机号码格式有误', trigger: 'blur'},
        { validator : checkPhone, trigger: 'blur'}
      ],
      full_name : [
        { min: 2, message: '姓名至少2个汉字', trigger: 'blur'},
        { pattern : /^[\u4e00-\u9fa5]{0,}$/, message: '姓名必须为中文汉字', trigger: 'blur'},
      ],
      qq : [
        { min: 5, message: 'QQ号至少为5位', trigger: 'blur'},
        { pattern : /^\d+$/, message: 'QQ号码必须为数字', trigger: 'blur'},
      ],
      email: [
        { pattern : /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/, message: '邮箱格式有误', trigger: 'blur'},
      ],
      age: [
        { pattern : /^\d+$/, message: '年龄必须为数字', trigger: 'blur'},
      ],
      year_income: [
        { pattern : /^[0-9]+(\.[0-9]{2})?$/, message: '年收入必须是整数或者两位小数', trigger: 'blur'}
      ],
      description: [
        { min: 5, max: 255, message: '线索描述长度为5-255个字符', trigger: 'blur'},
      ],
}

//加载全部的下拉菜单
const loadDicValue = (type_code) => {
  doGet("/api/dicValue/" + type_code, {}).then( resp => {
    console.log(resp);
    if (resp.data.code === 200) {
      if (type_code === 'appellation') {
        appellationOptions.value = resp.data.data;
      } else if (type_code === 'needLoan') {
        needLoanOptions.value = resp.data.data;
      } else if (type_code === 'intentionState') {
        intentionStateOptions.value = resp.data.data;
      } else if (type_code === 'clueState') {
        clueStateOptions.value = resp.data.data;
      } else if (type_code === 'source') {
        sourceOptions.value = resp.data.data;
      } else if (type_code === 'activity') {
        activityOptions.value = resp.data.data;
      } else if (type_code === 'product') {
        productOptions.value = resp.data.data;
      }
    }
  })
}

//加载当前负责人
const loadOwner = () => {
  doGet("/api/owner", {}).then(resp => {
    console.log(resp);
    if (resp.data.code === 200)  {
      ownerOptions.value = resp.data.data;
    }
  })
}
//加载当前登录人 添加时，初始化先设定当前登录者就是负责人
const loadLoginUser = () => {
  console.log("获取登录者信息");
  doGet("/api/login/info",{}).then( (resp) => {
    console.log(resp);
    clueQuery.owner_id = resp.data.data.id;
  })
}
//加载要编辑的线索数据
const loadClue = () => {
  let id =  route.params.id;
  if (id) { //id存在，id有值，id不为空，说明的编辑
    doGet("/api/clue/" + id, {}).then(resp => {
      if (resp.data.code === 200) {
        clueQuery = resp.data.data;
      }
    })
  }
}
//提交
const addClueSubmit = () => {
  clueRefForm.value.validate( (isValid) => {
    if (isValid) {
      let formData = new FormData;
      for(let field in clueQuery){
        formData.append(field,clueQuery[field]);
      }
      if(clueQuery.id > 0) {//编辑
        doPut("/api/clue", formData).then(resp => {
          if (resp.data.code === 200) {
            console.log(resp);
            messageTip("编辑成功", "success");
            //刷新
            reload();
            router.push("/dashboard/clue");
          } else {
            messageTip("编辑失败", "error");
          }
        })
      }else{ //提交
        doPost("/api/clue", formData).then(resp => {
          if (resp.data.code === 200) {
            console.log(resp);
            messageTip("提交成功", "success");
            //刷新
            reload();
            router.push("/dashboard/clue");
          } else {
            messageTip("提交失败", "error");
          }
        })
      }
    }
  })
}
</script>

<style scoped>

</style>